# -*- coding: utf-8 -*-
import sys
import logging
import pylons
from pylons import Response
from lxml import etree
from xadmin.model import *
from xadmin.lib.base import *

log = logging.getLogger(__name__)

class ProjectsController(BaseController):

    def add(self):
    	#Verificar que es correcto (DESEABLE)
    	#Pasear el documento y crear la instancia del objeto
    	#Validar los datos (Si es que no se verifica el xml)
    	#Hacer el save y commit para agregar a la BD
    	try:
            content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            if not content:
                content = request.params.get('xml')
            print content
            print 'hola'
            doc = etree.fromstring(content.encode())
            print etree.tostring(doc)
    	    #parseramos el doc
            name = doc.xpath('/project/name')[0].text
            description = doc.xpath('/project/description')[0].text
            print description
            client = doc.xpath('/project/client')[0].text
            print client
            start = doc.xpath('/project/start')[0].text
            print start
            end = doc.xpath('/project/end')[0].text
            #Guardamos el proyecto
            project = Project(name, description, client)
            project.start = start
            project.end = end
            Session.save(project)
            Session.commit()
            del response.headers['Content-Type']
            response.headers['Location'] = '/projects/%s' % project.id
            response.status_code = 201
            return
    	except:
            print "ERROR: ", sys.exc_info()[0]
            abort(400)

    def edit(self, id):
        try:
    	    content = request.body.read(int(request.environ['CONTENT_LENGTH']))
            print '--EDIT--'
            print content
            #print request.params.get('xml')
    	    doc = etree.fromstring(content)
    	    project = Session.query(Project).get(id)
            name = None
    	    if project:
                name = doc.xpath('/project/name')
                if name:
                    project.name = name[0].text
                description = doc.xpath('/project/description')
                if description:
                    project.description = description[0].text
                client = doc.xpath('/project/client')
                if client:
                    project.client = client[0].text
                start = doc.xpath('/project/start')
                if start:
                    project.start = start[0].text
                end = doc.xpath('/project/end')
                if end:
                    project.end = end[0].text
                Session.save(project)
                Session.commit()
                response.headers['Content-Type'] = 'text/xml; charset=utf-8'
                response.headers['Location'] = '/projects/%s' % project.id
                return
            else:
                abort(404)
    	except:
            abort(400)

    def view(self, id):
        c.project = Session.query(Project).get(id)
        if c.project:
            response.headers['content-type'] = 'text/xml; charset=utf-8'
            return render('/projects/view.mako')
        else:
            abort(404)

    def list(self):
        c.projects = Session.query(Project).all()
        print 'listing projects'
        response.headers['content-type'] = 'text/xml; charset=utf-8'
        return render('/projects/list.mako')

    def delete(self, id):
        print '--ADD--'
        content = request.body.read(int(request.environ['CONTENT_LENGTH']))
        print content
        print request.params
        project = Session.query(Project).get(id)
        if project:
            Session.delete(project)
            Session.commit()
            response.headers['Content-Type'] = 'text/xml; charset=utf-8'
            return
        else:
            abort(404)


